
package com.douyu.ocean.connect.router.error;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import com.douyu.ocean.connect.router.result.BaseApiResult;

import net.sf.json.JSON;
import net.sf.json.JSONObject;

@Slf4j
public class TxCrExceptionHandler implements HandlerExceptionResolver {

	private String exceptionPage = "/error/500";

	public ModelAndView resolveException(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex) {
		log.error("error", ex);
		BaseApiResult result = new BaseApiResult();
		result.setCode("0");
		result.setMsg(ex.getMessage());
		JSONObject jsonreturn = JSONObject.fromObject(result);
	
		returnMessage(response,jsonreturn.toString());
		return null;
		
	}

	public String getExceptionPage() {
		return exceptionPage;
	}

	public void setExceptionPage(String exceptionPage) {
		this.exceptionPage = exceptionPage;
	}
	
	public static void returnMessage(HttpServletResponse response, String content) {
		response.setCharacterEncoding("UTF-8");
		response.setContentType("application/json");
		PrintWriter pWriter = null;
		try {
			pWriter = response.getWriter();
			pWriter.write(content);
		} catch (IOException e) {
			log .error("returnMessage", e);
		} finally {
			if (pWriter != null) {
				pWriter.flush();
				pWriter.close();
			}
		}
	}

}
